<?php

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\Auth\ResetPasswordController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;

use App\Model\ProductCategory;
use App\Model\Manage;

class ProductCategoryController extends Controller
{
    protected static $field = [
        'id' => '编号',
        'create_time' => '创建时间',
        'update_time' => '更新时间',
        'create_user' => '创建人',
        'update_user' => '更新人',
        'rank' => '权重',
        'name' => '分类名称',
        'parent_id' => '父级分类名称',
        'status' => '状态'
    ];
    /**
     * @var int 数据表id
     */
    public $table_id = 8;

    /**
     * CaseController constructor.
     */
    public function __construct()
    {
        parent::__construct($this->table_id);

    }
//    public function level() {
//        return [
//            1=>'一级分类',
//            2=>'二级分类',
//            3=>'三级分类'
//        ];
//    }
    /**
     * 产品分类列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index() {
        #判断权限
        if($this->rule['view'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }

        $obj = new ProductCategory;
        $check_time = Input::get('check_time');
        $category = Input::get('category');
        $keyword = Input::get('keyword');
        $time = Input::get('create_time');
        $type = Input::get('type');
        $code = Input::get('code');
        if(Input::has('category') && Input::has('keyword')) {
            if(Input::get('category') === 'create_user' || Input::get('category') === 'update_user') {
                $user = Manage::select('id')->where('username','like',"%$keyword%")->get();
                $obj = $obj->whereIn(Input::get('category'),$user);
            }
            else if(Input::get('category') === 'parent_id') {
                $parent = ProductCategory::select('id')->where('name','like',"%$keyword%")->get();
                $obj = $obj->whereIn('parent_id',$parent);
            }
            else {
                $obj = $obj->where(Input::get('category'),'like',"%$keyword%");
            }
        }
        if(Input::has('check_time')) {
            $start_time = date("Y-m-d 00:00:00",strtotime(substr($time , 0 , 10)));
            $end_time = date("Y-m-d 23:59:59",strtotime(substr($time,-10)));
            $obj = $obj->whereBetween('create_time',[$start_time,$end_time]);
        }
        //升降排序
        if(Input::has('type') && Input::has('code')) {
            if($code == 0) {
                $obj = $obj->orderBy($type,'asc');
            }
            if($code == 1) {
                $obj = $obj->orderBy($type,'desc');
            }
        }

        $data = $obj->paginate(10);
        $field = self::$field;
        return view('manage.product.category.index',compact('data','field','check_time','category','keyword','time','type','code'));
    }

    /**
     * 载入添加页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create() {
        #判断权限
        if($this->rule['add'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $first = ProductCategory::where('status',1)->get();
        $category = $this->getCategoryList($first);
        $cate = $this->tree($first,'id','name','parent_id');
        return view('manage.product.category.create',compact('first','cate'));
    }

    /**
     * 写入数据
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request) {
        #判断权限
        if($this->rule['add'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $level = null;
        $input = $request->only('user_id','parent','name','rank');
//        dump($input);
        if(empty($input['name'])) {
            return redirect()->back()->withInput()->withErrors('分类名不能为空!');
        }
        if(ProductCategory::where('parent_id',$input['parent'])->where('name',$input['name'])->first()) {
            return redirect()->back()->withInput()->withErrors('分类已存在!');
        }
        if($input['parent'] == 0) {
            $level = 1;
        }else {
            $par = ProductCategory::where('id',$input['parent'])->first();
//            dump($par);
            $level = (int)$par->level+1;
        }
        if(ProductCategory::insert([
            'rank' => $input['rank'],
            'create_user' => $input['user_id'],
            'name' =>$input['name'],
            'parent_id' => $input['parent'],
            'level' => $level
        ])) {
            return Redirect::to('manage/product_category');
        }
        else {
            return redirect()->back()->withInput()->withErrors('添加失败!');
        }
    }

    /**
     * 载入更新页
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id) {
        #判断权限
        if($this->rule['update'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $list = ProductCategory::find($id);
        $first = ProductCategory::where('status',1)->get();
        $cate = $this->tree($first,'id','name','parent_id');
//        dump($cate);
        return view('manage.product.category.edit',compact('cate','list'));
    }

    /**
     * 更新数据
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update(Request $request,$id) {
        #判断权限
        if($this->rule['update'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $input = $request->only('user_id','parent','name','rank');
//        dump($input);
        if(empty($input['name'])) {
            return redirect()->back()->withInput()->withErrors('分类名不能为空!');
        }
        if($id == $input['parent']) {
            return redirect()->back()->withInput()->withErrors('不能选自己作为父级分类!');
        }
//        if(ProductCategory::where('parent_id',$input['parent'])->where('name',$input['name'])->first()) {
//            return redirect()->back()->withInput()->withErrors('分类已存在!');
//        }
        if($input['parent'] == 0) {
            $level = 1;
        }else {
            $par = ProductCategory::where('id',$input['parent'])->first();
//            dump($par);
            $level = (int)$par->level+1;
        }
        if(ProductCategory::where('id',$id)->update([
            'rank' => $input['rank'],
            'update_user' => $input['user_id'],
            'name' =>$input['name'],
            'parent_id' => $input['parent'],
            'level' => $level
        ])) {
            return Redirect::to('manage/product_category');
        }
        else {
            return redirect()->back()->withInput()->withErrors('更新失败!');
        }
    }

    /**
     * 修改分类状态
     * @return array
     */
    public function status()
    {
        #判断权限
        if($this->rule['update'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }
        $id = Input::get('id');
        $status = Input::get('status');

        if ($status == 1) {
            $del = ProductCategory::where('id', $id)->update(['status' => 1, 'update_user' => session('user.id')]);
            $msg = '启用成功！';
        } else {
            $child = ProductCategory::where('parent_id',$id)->where('status',1)->get();
            if(count($child) == 0) {
                $del = ProductCategory::where('id', $id)->update(['status' => 0, 'update_user' => session('user.id')]);
                $msg = '禁用成功！';
            }else {
                return [
                    'code' => 102,
                    'msg' => '设置失败,请先禁用子分类！'
                ];
            }
        }
        if (!$del) {
            return [
                'code' => 101,
                'msg' => '设置失败！'
            ];
        }
        return [
            'code' => 100,
            'msg' => $msg
        ];
    }

    /**
     * 删除数据
     * @param $id
     * @return array
     */
    public function destroy() {
        #判断权限
        if($this->rule['delete'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }
        $id = Input::get('id');
        $child = ProductCategory::where('parent_id',$id)->get();
        if(count($child) == 0) {
            $res = ProductCategory::where('id',$id)->delete();
            if($res){
                return [
                    'code' => 100,
                    'msg' => '删除成功！'
                ];
            }else{
                return [
                    'code' => 101,
                    'msg' => '删除失败！'
                ];
            }
        }
        else {
            return [
                'code' => 102,
                'msg' => '删除失败,请先删除子分类!'
            ];
        }

    }

    /**
     * 3级分类层级排列
     * @param $category
     * @param int $level
     * @param int $parent_id
     * @return null
     */
    public function getCategoryList($category, $level = 1, $parent_id = 0)
    {
        $list = null;
        foreach ($category as $key => $value){
            if($parent_id > 0 && $parent_id != $value->parent_id){
                continue;
            }
            if($value->level == $level){
                $list[$value->id]['id'] = $value->id;
                $list[$value->id]['name'] = $value->name;
                $list[$value->id]['parent_id'] = $value->parent_id;
//                $list[$value->id]['picture'] = $this->domain . $this->path['category_picture'] . $value->picture;
                if($level < 3) {
                    $tmpList = $this->getCategoryList($category, $level + 1, $value->id);
                    if(!empty($tmpList)) {
                        foreach ($tmpList as $k => $v) {
                            if ($value->id == $v['parent_id']) {
                                $list[$value->id]['child'][] = $v;
                            }
                        }
                    }
                }
            }
        }
        return $list;
    }

    /**
     * 无限级分类层级排列
     * @param $data
     * @param $idKey
     * @param $nameKey
     * @param $parentKey
     * @return array
     */
    function tree($data, $idKey, $nameKey, $parentKey)
    {
        $treeArray = array(); # 树形数组
        $linearStructure = array(); # 线性关系数组
        # 遍历数据集合
        foreach ($data as $val) {
            if (!empty($val[$parentKey])) {
                # 如果没有线性关系的节点，添加新的线性关系，并将节点添加到树形数组中
                if (!isset($linearStructure[$val[$parentKey]])) {
                    $linearStructure[$val[$idKey]] = [$val[$parentKey]];
                    if (isset($treeArray[$val[$parentKey]])) {
                        $treeArray[$val[$parentKey]]['child'][$val[$idKey]]['name'] = $val[$nameKey];
                    } else {
                        $treeArray[$val[$parentKey]]['child'][$val[$idKey]]['name'] = $val[$nameKey];
                    }
                    continue;
                }
                # 如果线性关系存在则更新线性关系，并将节点按线性关系插入到树形数组的指定位置
                $linear = $linearStructure[$val[$parentKey]];
                $linear[] = $val[$parentKey];
                $linearStructure[$val[$idKey]] = $linear;
                $pointer = &$treeArray;
                foreach ($linear as $node) {
                    $pointer = &$pointer[$node]['child'];
                }
                # 移动子节点到当前节点
                if (isset($treeArray[$val[$parentKey]])) {
                    $pointer = $treeArray[$val[$parentKey]]['child'];
                    unset($treeArray[$val[$parentKey]]);
                    continue;
                }
                # 插入子节点
                $pointer[$val[$idKey]]['name'] = $val[$nameKey];
                continue;
            }
            $treeArray[$val[$idKey]]['name'] = $val[$nameKey];
        }
        unset($linearStructure);
        return $treeArray;
    }
}
